<template>
  <div class v-loading="loading">
    <div class="clearfix">
      <el-dialog
        title="添加管理员"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        :visible.sync="dialogFormVisible"
        class="tl size_13"
        width="800px"
      >
        <el-form :model="data" :rules="dataYZ" ref="data" label-width="120px">
          <el-form-item label="角色" prop="role_id">
            <el-col :span="12">
              <el-select
                v-model="data.role_id"
                placeholder="请选择"
                @change="handChange"
                style="width: 100%"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-col>
          </el-form-item>

          <el-form-item label="账号" prop="username">
            <el-col :span="12">
              <el-input
                placeholder="请输入账号"
                v-model="data.username"
                :disabled="updateAdmin"
                clearable
              ></el-input>
            </el-col>
          </el-form-item>

          <el-form-item label="昵称" prop="username">
            <el-col :span="12">
              <el-input
                placeholder="请输入昵称"
                v-model="data.nick_name"
                clearable
              ></el-input>
            </el-col>
          </el-form-item>

          <el-form-item v-if="!updateAdmin" label="密码" prop="password">
            <el-col :span="12">
              <el-input
                type="password"
                placeholder="请输入密码"
                v-model="data.password"
                clearable
              ></el-input>
            </el-col>
          </el-form-item>

          <el-form-item v-if="!updateAdmin" label="确认密码" prop="repassword">
            <el-col :span="12">
              <el-input
                type="password"
                placeholder="请输入密码"
                v-model="data.repassword"
                clearable
              ></el-input>
            </el-col>
          </el-form-item>

          <el-form-item label="电话" prop="tel">
            <el-col :span="12">
              <el-input
                placeholder="请输入手机号"
                v-model="data.tel"
                clearable
              ></el-input>
            </el-col>
          </el-form-item>

          <el-form-item label="用户名" prop="im">
            <el-col :span="12">
              <el-input
                placeholder="请选择用户"
                :rows="3"
                v-model="im"
                :disabled="true"
                clearable
              ></el-input>
            </el-col>
            <el-col :span="4" :offset="1">
              <el-button
                :loading="$store.state.isLoading"
                size="medium"
                type="primary"
                @click="xzshop('xzuser')"
                >选择用户</el-button
              >
            </el-col>
          </el-form-item>

          <el-form-item>
            <el-button
              :loading="$store.state.isLoading"
              size="mini"
              type="primary"
              @click="addSave('data')"
              >确定</el-button
            >
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>

    <keep-alive>
      <component
        :is="current"
        :show="shows"
        :isAll="false"
        :isPart="true"
        showType="list"
        @sendShop="getSend"
        @isshow="getShow"
      ></component>
    </keep-alive>

    <tableComponents
      :isShow="false"
      @toAdd="openDio"
      :isHaveExport="false"
      :isHavePagination="false"
    >
      <template v-slot:table>
        <el-table
          ref="multipleTable"
          header-row-class-name="head_color"
          :data="list"
          v-loading="loading"
          stripe
          tooltip-effect="dark"
          style="width: 99.9%"
        >
          <el-table-column label="管理员" min-width="100">
            <template slot-scope="scope">{{ scope.row.username }}</template>
          </el-table-column>

          <el-table-column label="角色" min-width="100">
            <template slot-scope="scope">{{ scope.row.role_name }}</template>
          </el-table-column>

          <el-table-column label="电话" min-width="150">
            <template slot-scope="scope">{{ scope.row.tel }}</template>
          </el-table-column>

          <el-table-column label="绑定用户名" min-width="150">
            <template slot-scope="scope">{{ scope.row.im_cn }}</template>
          </el-table-column>

          <el-table-column label="登录IP" min-width="150">
            <template slot-scope="scope">{{ scope.row.last_ip }}</template>
          </el-table-column>

          <el-table-column label="登录时间" min-width="150">
            <template slot-scope="scope">{{
              scope.row.last_login | getTimeFormat
            }}</template>
          </el-table-column>

          <el-table-column label="是否通知" min-width="100">
            <template slot-scope="scope">
              <switchc
                :value="scope.row.is_notice"
                @change="handlenotice($event, scope.row.id)"
                text="on|off"
              ></switchc>
            </template>
          </el-table-column>

          <el-table-column
            label="是否客服"
            min-width="100"
            v-if="
              $store.state.plugin &&
              $store.state.plugin.btkfxt &&
              $store.state.plugin.btkfxt.is_open == 1
            "
          >
            <template slot-scope="scope">
              <switchc
                :value="scope.row.service"
                @change="handleservice($event, scope.row.id)"
                text="on|off"
              ></switchc>
            </template>
          </el-table-column>

          <el-table-column label="是否显示" min-width="100">
            <template slot-scope="scope">
              <switchc
                :value="scope.row.show"
                @change="handleSwitch($event, scope.row.id)"
                text="on|off"
              ></switchc>
            </template>
          </el-table-column>

          <el-table-column label="操作" min-width="150">
            <template slot-scope="scope">
              <el-button
                :loading="$store.state.isLoading"
                size="mini"
                @click="showEditDialog(scope.$index, scope.row)"
                >编辑</el-button
              >
              <el-button
                :loading="$store.state.isLoading"
                size="mini"
                @click="deleteNew(scope.$index, scope.row.id)"
                type="danger"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
    </tableComponents>
  </div>
</template>
<script>
import switchc from "@/components/currency/Swich";
import HeadTitle from "@/components/currency/HeadTitle.vue";
import xzuser from "@/components/currency/xz_user.vue";
export default {
  data() {
    // eslint-disable-next-line no-useless-escape
    var ex = /^[A-Za-z0-9\-\_]+$/;
    var checkUser = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      } else {
        //  setTimeout(() => {
        if (!this.$fnc.regexp(ex, value)) {
          callback(new Error("用户名非法"));
        } else {
          callback();
        }
        // }, 1000)
      }
    };

    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.data.repassword !== "") {
          this.$refs.data.validateField("repassword");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.data.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      show: false,
      myshow: false,
      list: [],
      adminId: "",
      dialogFormVisible: false,
      updateAdmin: false,
      uddateIndex: "",
      options: [
        {
          value: "",
          label: "",
        },
      ],
      value: "",
      data: {
        username: "",
        password: "",
        tel: "",
        role_id: "3",
        last_ip: "",
        last_login: "",
        nick_name: "",
        im: "",
      },
      im: "",
      dataYZ: {
        username: [{ validator: checkUser, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur", min: 6 }],
        repassword: [{ validator: validatePass2, trigger: "blur", min: 6 }],
        tel: [{ min: 11, max: 11, message: "手机格式错误", trigger: "blur" }],
      },
      current: {},
      shows: false,
    };
  },
  components: {
    switchc,
    HeadTitle,
    xzuser,
  },
  methods: {
    xzshop(str) {
      this.current = str;
      this.shows = true;
    },
    getShow(val) {
      this.shows = val;
    },
    getSend(row, obj) {
      if (obj == "obj") {
        var str = "";
        for (let i of row) {
          str += i.username + ",";
        }
        str = str.slice(0, -1);
        this.im = str;
      } else {
        this.im = row.username;
        this.data.im = row.id;
      }
    },
    handlenotice(val, id) {
      var params = {};
      params["id"] = id;
      val == true ? (params["is_notice"] = 1) : (params["is_notice"] = 0);
      this.$api.getAdminuser.change_notice(params).then((res) => {
        if (res.data.status == 0) {
          this.$fnc.alertError(res.data.code_desc, res.data.result); //失败弹出框
        }
      });
    },
    openDio() {
      this.dialogFormVisible = true;
      (this.updateAdmin = false), (this.showImg = false);
      this.adminId = "";
      this.data = {
        username: "",
        tel: "",
      };
    },
    getAdminDetails(id) {
      var data = {};
      data["id"] = id;
      this.$api.getAdminuser.getInfo(data).then(res => {
        res.data.result.last_login = res.data.result.last_login + "000";
        this.data = res.data.result;
      });
    },
    getNewsAll() {
      this.loading = true;
      var data = { cate_id: "" };
      this.$api.getAdminuser.getAdminuserList(data).then((res) => {
        if (res.data.code == 200) {
          this.list = res.data.result;
        }
      });
      this.loading = false;
    },
    handleservice(val, id) {
      var params = {};
      params["id"] = id;
      val == true ? (params["service"] = 1) : (params["service"] = 0);
      this.$api.getAdminuser.myChangeservice(params).then((res) => {
        if (res.data.status == 0) {
          this.$fnc.alertError(res.data.code_desc, res.data.result); //失败弹出框
        }
      });
    },
    handleSwitch(val, id) {
      var params = {};
      params["id"] = id;
      val == true ? (params["show"] = 1) : (params["show"] = 0);
      this.$api.getAdminuser.myChangeShow(params).then((res) => {
        if (res.data.status == 0) {
          this.$fnc.alertError(res.data.code_desc, res.data.result); //失败弹出框
        }
      });
    },
    deleteNew(index, id) {
      this.$swal({
        title: "您确定要删除这条信息吗",
        text: "删除后将无法恢复，请谨慎操作！",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "是的，我要删除",
        cancelButtonText: "容我三思",
      }).then((willDelete) => {
        if (willDelete.value) {
          var data = { id };
          this.$api.getAdminuser.myDelete(data).then((res) => {
            if (res.data.code == 200) {
              this.$swal("删除成功！", "您已经删除了这条信息。", "success");
              this.list.splice(index, 1);
            } else {
              this.$swal("删除失败！", "出错啦！", "success");
            }
          });
        } else if (willDelete.dismiss == "cancel") {
          this.$swal("已取消", "您取消了删除操作", "error");
        }
      });
    },
    handChange(val) {
      this.data.role_id = val;
    },
    showEditDialog(index, row) {
      this.updateAdmin = true;
      this.uddateIndex = index;
      this.adminId = row.id;
      this.dialogFormVisible = true;
      this.data = row;
      this.im = row.im_cn;
    },
    addSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var params = {};
          params["role_id"] = this.data.role_id;
          params["tel"] = this.data.tel;
          if (this.adminId) {
            this.$api.getAdminuser.myUpdate(this.data).then((res) => {
              if (res.data.code == 200 && res.data.result != null) {
                this.$fnc.alertSuccess({ text: "修改成功" }); //成功弹出框
                // this.dialogFormVisible = false;
                // this.getNewsAll();
                this.list[this.uddateIndex] = this.data;
              } else {
                this.$fnc.alertError(res.data.result); //失败弹出框
              }
            });
          } else {
            params["username"] = this.data.username;
            params["password"] = this.$getCode(this.data.password);
            params["nick_name"] = this.data.nick_name;
            this.$api.getAdminuser.mySave(params).then((res) => {
              if (res.data.code == 200 && res.data.result != null) {
                this.$fnc.alertSuccess({ text: "添加成功" }); //成功弹出框
                this.data.id = res.data.result;
                this.dialogFormVisible = false;
                this.getNewsAll();
              } else {
                this.$fnc.alertError(res.data.result); //失败弹出框
              }
            });
          }
          setTimeout(() => {
            if (this.data.im) {
              var par_value = {
                user_id: this.data.im,
                admin_id: this.data.id,
              };
              this.$api.getAdminuser.setAdminIm(par_value).then((res) => {
                if (res.data.code == 200) {
                  // 成功
                  this.dialogFormVisible = false;
                  this.getNewsAll();
                } else {
                  this.$fnc.alertError(res.data.result);
                  this.dialogFormVisible = false;
                  this.getNewsAll();
                }
              });
            }
          }, 500);
        } else {
          return false;
        }
      });
    },
    getRoleList() {
      var data = {};
      this.$api.getAdminuser.getRoleOption(data).then((res) => {
        this.options = res.data.result;
      });
    },
  },
  beforeCreate() {
    this.loading = true; //数据未加载之前调用loading
  },
  created() {
    this.getNewsAll();
    this.loading = false;
  },
  computed: {},
  mounted() {
    this.getRoleList();
    if (this.adminId) {
      this.getAdminDetails(this.adminId);
    }
  },
  watch: {},
};
</script>
